package com.zuowei.ycy.user.ui.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.EditText;

import com.and.yzy.frame.util.AppManger;
import com.and.yzy.frame.util.MatchStingUtil;
import com.and.yzy.frame.util.RetrofitUtils;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.config.UserManger;
import com.zuowei.ycy.user.domain.UserInfo;
import com.zuowei.ycy.user.http.RegisterLog;
import com.zuowei.ycy.ui.BaseAty;
import com.zuowei.ycy.user.ui.MainAty;
import com.zuowei.ycy.user.util.AppJsonUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yzy on 2016/4/19.
 */
public class LoginAty extends BaseAty {

    @Bind(R.id.tv_acount)
    EditText mTvAcount;
    @Bind(R.id.et_pwd)
    EditText mEtPwd;

    private MyThreedReceiver receiver;
    @Override
    public int getLayoutId() {
        return R.layout.login_aty;
    }

    @Override
    public void initData() {
        ShareSDK.initSDK(this);
        receiver = new MyThreedReceiver();
        IntentFilter filter = new IntentFilter("BROADCAST_ACTION_SOCIALIZE_LOGIN");
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver!=null){
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void requestData() {

    }


    @OnClick({R.id.tv_commit, R.id.tv_forget_pwd, R.id.tv_regist,R.id.imgv_login_weibo,R.id.imgv_login_qq,R.id.imgv_login_weixin})
    @Override
    public void btnClick(View view) {
        super.btnClick(view);
        switch (view.getId()) {
            case R.id.tv_commit:

                if (mTvAcount.getText().toString().equals("")) {
                    showToast("账号不能为空!");
                    mTvAcount.requestFocus();
                    return;
                }
                if (!MatchStingUtil.isMobile(mTvAcount.getText().toString().trim())) {
                    showToast("账号号格式不正确!");
                    mTvAcount.requestFocus();
                    return;
                }


                if (mEtPwd.getText().toString().equals("")) {
                    showToast("密码不能为空!");
                    mEtPwd.requestFocus();
                    return;
                }


                showLoadingDialog(null);
                doHttp(RetrofitUtils.createApi(RegisterLog.class).Login(mTvAcount.getText().toString().trim(), mEtPwd.getText().toString().trim()), 1);

                break;
            case R.id.tv_forget_pwd:
                startActivity(ForgetPwdAty.class, null);

                break;
            case R.id.tv_regist:
                startActivityForResult(RegistAty.class, null, 1);

                break;
            case R.id.imgv_login_weibo:
                Platform platWeibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);
                authorize(platWeibo);
                break;
            case R.id.imgv_login_qq:
                Platform platQQ= ShareSDK.getPlatform(this, "QQ");
                authorize(platQQ);
                break;
            case R.id.imgv_login_weixin:
                Platform platWx = ShareSDK.getPlatform(this, Wechat.NAME);
                authorize(platWx);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void onSuccess(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {

        showToast("登录成功");
        UserManger.setIsLogin(true);
        UserManger.setUserInfo(AppJsonUtil.getObject(result, UserInfo.class));
        if (AppManger.getInstance().isAddActivity(MainAty.class)) {
            setResult(RESULT_OK);
            finish();
        } else {
            setHasAnimiation(false);
            startActivity(MainAty.class, null);
            finish();
        }


        super.onSuccess(result, call, response, what);
    }

//    private long oldTime;
//
//    @Override
//    public void onBackPressed() {
//        //        super.onBackPressed();
//        long newtime = System.currentTimeMillis();
//        if (newtime - oldTime > 3000) {
//            oldTime = newtime;
//            showToast("连按两次返回桌面");
//        } else {
//            //            AppManager.getInstance().killAllActivity();
//            setHasAnimiation(false);
//            AppManger.getInstance().AppExit(this);
//        }
//    }

    private boolean isValid = false;;
    private void authorize(Platform plat) {
        if (plat == null) {
            return;
        }
        // 判断指定平台是否已经完成授权
        if (plat.isValid()) {
            String userId = plat.getDb().getUserId();
            String nickname = plat.getDb().getUserName();
            System.out.println("============  " + userId + "     " + nickname);
            if (userId != null) {
                isValid = true;
                System.out.println("============  " + userId + "     " + nickname);
                // 登录方法
                showToast("授权成功");
//                member.threeLogin(userId, nickname, this);
               showLoadingDialog("");
               doHttp(RetrofitUtils.createApi(RegisterLog.class).threeLogin(userId),5);
            }
        }
        plat.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {

            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                System.out.println("==============  " + arg0.getDb().getUserId());
//                 通过广播对第三方帐号进行绑定

                if (!isValid) {
                    Intent intent = new
                            Intent("BROADCAST_ACTION_SOCIALIZE_LOGIN");
                    intent.putExtra("platformName",
                            arg0.getDb().getPlatformNname());
                    intent.putExtra("open_id", arg0.getDb().getUserId());
                    intent.putExtra("user_name", arg0.getDb().getUserName());
                    sendBroadcast(intent);
                }
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {

            }

        });
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(false);
        // 获取用户资料
        plat.showUser(null);
    }

    private class MyThreedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("BROADCAST_ACTION_SOCIALIZE_LOGIN")) {
                String userId = intent.getStringExtra("open_id");
                String nickname =intent.getStringExtra("user_name");
                System.out.println("============  " + userId + "     " + nickname);
                if (userId != null) {
                    System.out.println("============  " + userId + "     " + nickname);
                    // 登录方法
                    showToast("授权成功");
//                    member.threeLogin(userId, nickname, this);
                    showLoadingDialog("");
                    doHttp(RetrofitUtils.createApi(RegisterLog.class).threeLogin(userId),5);
                }
            }

        }

    }

}
